import { accountLoginRequest, getUserInfoById, getUserMenusByRoleId } from "@/service/login/login";
import { defineStore } from "pinia";
import type { IAccount } from '@/types'
import { localCache } from "@/utils/cache";
import { mapMenusToRoutes } from '@/utils/map-menus'
import router from "@/router";
import { LOGIN_TOKEN } from "@/global/constants";
import useMainStore from "../main/main";

// const LOGIN_TOKEN = 'login/token'


interface ILoginState {
  token: string,
  userInfo: any,
  userMenus: any
  // userInfo: {
  //   role: {
  //     id: number,
  //   }
  // }
}

const useLoginStore = defineStore<string, {}>("login", {
  state: (): ILoginState => ({
    token: '',
    userInfo: {},
    userMenus: []
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      // 1. 账号登录 ,获取token信息
      const loginResult = await accountLoginRequest(account)
      const id = loginResult.data.id
      const name = loginResult.data.name
      this.token = loginResult.data.token
      localCache.setCache(LOGIN_TOKEN, this.token)

      // 2. 进行本地缓存
      // localCache.setCache(LOGIN_TOKEN, this.token)

      // 2. 获取登录用户的相信信息,角色信息
      const userInfoResult = await getUserInfoById(id)
      const userInfo = userInfoResult.data
      this.userInfo = userInfo

      // 3. 根据角色请求用户的权限(菜单menu)
      const userMenusResult = await getUserMenusByRoleId(this.userInfo.role.id)
      const userMenus = userMenusResult.data
      this.userMenus = userMenus

      // 4. 进行本地缓存
      localCache.setCache('userInfo', userInfo)
      localCache.setCache('userMenus', userMenus)

      // 请求所有的roles
      const mainStore = useMainStore()
      mainStore.fetchEntireRolesAction()

      // 5. 将用户菜单映射成路由,动态获取
      const routes = mapMenusToRoutes(userMenus)
      routes.forEach(route => router.addRoute('main', route))

      // 5. 进行路由跳转
      router.push('/main')

    },
    // 该方法主要处理登录成功以后刷新页面,防止出现页面空白的情况 
    loadLocalCacheAction() {
      // 1. 用户进行页面刷新才能加载  
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')

      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        const mainStore = useMainStore()
        mainStore.fetchEntireRolesAction()

        // 2. 动态添加路由
        const routes = mapMenusToRoutes(userMenus)
        routes.forEach(route => router.addRoute('main', route))
      }
    }
  }
})

export default useLoginStore  